/*
 *  Copyright 2005 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.common.parsers.pdf;

import com.blandware.atleap.common.parsers.SpecificPlainTextExtractor;
import com.blandware.atleap.common.parsers.exception.PlainTextExtractorException;
import org.pdfbox.pdmodel.PDDocument;
import org.pdfbox.util.PDFTextStripper;

import java.io.InputStream;
import java.io.Writer;
import java.io.IOException;

/**
 * An extractor that extracts a plain text from PDF documents.
 *
 * @see SpecificPlainTextExtractor
 * @author Roman Puchkovskiy <a href="mailto:roman.puchkovskiy@blandware.com">
 * &lt;roman.puchkovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.4 $ $Date: 2007/10/02 18:06:48 $
 */
public class PDFPlainTextExtractor implements SpecificPlainTextExtractor {
    public PDFPlainTextExtractor() {
    }

    /**
     * Extracts a plain text from a PDF document.
     *
     * @param input the input stream that supplies a PDF document for extraction
     * @param output the writer that will accept the extracted text
     * @param encoding ignored
     * @throws PlainTextExtractorException throwed on exception raised during
     * extracting
     */
    public void extract(InputStream input, Writer output, String encoding)
            throws PlainTextExtractorException {
        // TODO: Find out why the stripper hangs on some PDFs
        // TODO: Workaround encoding problems
        PDDocument document = null;
        try {
            PDFTextStripper stripper = new PDFTextStripper();

            document = PDDocument.load(input);
            if (document.isEncrypted()) {
                // Trying do decrypt with an empty password
                document.decrypt("");
            }
            stripper.writeText(document, output);
        } catch (Throwable e) {
            throw new PlainTextExtractorException(e);
        } finally {
            try {
                if (document != null) {
                    document.close();
                }
            } catch (IOException e) {
                // swallow
            }
        }
    }

    /**
     * @see com.blandware.atleap.common.parsers.SpecificPlainTextExtractor#getUsedEncoding()
     */
    public String getUsedEncoding() {
        return null;
    }
}
